#!/bin/bash

set -e
set -o pipefail

# Uncomment below option for debugging
#set -x

SLEEP=$1

if [[ "$SLEEP" == "" ]]; then
    echo "sm-wait: ERROR: missing argument"
    exit 1
fi

if [[ "$SLEEP" == "stop" ]]; then
    echo "sm-wait: Stopping all waiting processes." \
      | tee /proc/1/fd/1
    touch /tmp/sm-wait-stopped
    exit 0
fi

if [[ "$SLEEP" == "list" ]]; then
    ps -fC sm-wait
    exit 0
fi

if [[ "$SLEEP" == 0 ]]; then
    exit 0
fi

terminate() {
    echo "sm-wait: Terminated."
    exit 2
}

trap terminate SIGTERM
trap terminate SIGINT

echo "sm-wait: Waiting for $SLEEP seconds to let you prepare you connection. "\
  "Once you're ready, run 'sm-wait stop' inside the container or 'sm-local-ssh-* stop-waiting' "\
  "from your local machine."

for loop in $(seq 1 1 "$SLEEP") 
do
    if [[ -f /tmp/sm-wait-stopped ]]; then
      sleep 2  # let `sm-wait stop` exit successfully before we stop the container
      echo "sm-wait: Successfully stopped. Remove /tmp/sm-wait-stopped to start again."
      exit 0
    fi
    sleep 1
    SSM_PID=$(pgrep -f amazon-ssm-agent || echo "")
    if [[ "$SSM_PID" == "" ]]; then
      AGENT_INFO="SSM Agent has NOT been started yet."
    else
      # TODO: show /var/log/amazon/ssm/*.log in case there are errors
      AGENT_INFO="SSM Agent has been already started."
    fi

    if [[ "$((loop % 10))" == "0" ]]; then
      echo "sm-wait: Still waiting ($loop)... $AGENT_INFO"
    fi
done

echo "sm-wait: Waiting complete. No 'stop' command received. Had SSM initialization failed? Do you need to increase timeout?"
